<template>
	<swiper class="home-swiper" @change="change" :current="activeIndex">
		<swiper-item class="swiper-item" v-for="(item,index) in tab" :key="index">
			<scroll-view scroll-y="true" class="list-item">
				<list-item :list="listCatchData[index]" @loadmore="loadmore" :load="load[index]"></list-item>
			</scroll-view>
		</swiper-item>
	</swiper>
</template>

<script>
	import listItem from './list-item.vue'
	export default {
		name: "list",
		props: {
			tab: {
				type: Array,
				default () {
					return []
				}
			},
			activeIndex: {
				type: Number,
				default: 0
			}
		},
		data() {
			return {
				list: [],
				listCatchData: {},
				load: {},
				pageSize: 10
			};
		},
		watch: {
			tab(newVal) {
				if (newVal.length === 0) return;
				this.listCatchData = {};
				this.load = {};
				this.getList(this.activeIndex);
			}
		},
		created() {
			// TODO tab还没拿到
			uni.$on('update_article', (e) => {
				if (e === 'follow') {
					this.listCatchData = {};
					this.load = {};
					this.getList(this.activeIndex);
				}
			})
		},
		components: {
			listItem
		},
		methods: {
			change(e) {
				const {
					current
				} = e.detail;

				this.$emit('change', current);
				// TODO 当数据不存在 或者长度是0 的情况下 才去请求数据
				if (!this.listCatchData[current] || this.listCatchData[current].length === 0) {
					this.getList(current);
				}
			},
			loadmore() {
				if (this.load[this.activeIndex].loading === 'noMore') return;
				this.load[this.activeIndex].page++;
				console.log('触发上拉');
				this.getList(this.activeIndex);
			},
			getList(current) {
				if (!this.load[current]) {
					this.load[current] = {
						page: 1,
						loading: 'loading'
					}
				}
				console.log(this.load[current].page, '123123');
				this.$api.get_list({
					name: this.tab[current].name,
					page: this.load[current].page,
					pageSize: this.pageSize
				}).then(res => {
					console.log(res);
					const {
						data
					} = res;
					if (data.length === 0) {
						let oldLoad = {};
						oldLoad.loading = 'noMore';
						oldLoad.page = this.load[current].page;
						this.$set(this.load, current, oldLoad);
						// 强制渲染页面
						this.$forceUpdate();
						return;
					}
					let oldList = this.listCatchData[current] || [];
					oldList.push(...data);
					this.$set(this.listCatchData, current, oldList);
				})
			}
		},
	}
</script>

<style lang="scss">
	.home-swiper {
		height: 100%;

		.swiper-item {
			height: 100%;
			overflow: hidden;

			.list-item {
				height: 100%;
			}
		}
	}
</style>
